﻿using ERP.RBAC;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ERP.Web.Controllers
{
    public class PermissionController : Controller
    {
        private readonly IPermissionsService _permissionsService;

        public PermissionController(IPermissionsService permissionsService)
        {
            _permissionsService = permissionsService;
        }

        public IActionResult ShowPermission()
        {
            return View();
        }

        /// <summary>
        /// 权限编辑页面
        /// </summary>
        /// <param name="id">权限ID，为空表示添加新权限</param>
        /// <returns></returns>
        public async Task<IActionResult> EditPermission(int? id)
        {
            // 如果有ID，则是编辑模式
            if (id.HasValue && id.Value > 0)
            {
                try
                {
                    var permission = await _permissionsService.GetPermissionById(id.Value);
                    if (permission == null)
                    {
                        TempData["ErrorMessage"] = $"找不到ID为{id}的权限";
                        return RedirectToAction("ShowPermission");
                    }

                    ViewBag.Title = "编辑权限";
                    ViewBag.IsEdit = true;
                    ViewBag.Permission = permission;
                    return View();
                }
                catch (Exception ex)
                {
                    TempData["ErrorMessage"] = $"获取权限信息失败: {ex.Message}";
                    return RedirectToAction("ShowPermission");
                }
            }
            else
            {
                // 添加模式
                ViewBag.Title = "添加权限";
                ViewBag.IsEdit = false;
                ViewBag.Permission = null;
                return View();
            }
        }

        [HttpGet]
        public async Task<JsonResult> GetPermission()
        {
            var data = await _permissionsService.GetPermission();
            return Json(new { code = 0, msg = "", count = data.Count, data = data });
        }

        [HttpGet]
        public async Task<JsonResult> GetPermissionById(int id)
        {
            try
            {
                if (id <= 0)
                {
                    return Json(new { success = false, message = "无效的权限ID" });
                }
                
                var permission = await _permissionsService.GetPermissionById(id);
                if (permission == null)
                {
                    return Json(new { success = false, message = $"找不到ID为{id}的权限" });
                }
                
                return Json(new { success = true, data = permission });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取权限信息失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<JsonResult> CreatePermission(string permissionName)
        {
            try
            {
                Console.WriteLine($"创建权限方法被调用，权限名称={permissionName}");
                
                if (string.IsNullOrEmpty(permissionName))
                {
                    Console.WriteLine("权限名称为空");
                    return Json(new { success = false, message = "权限名称不能为空" });
                }
                
                // 创建新的权限对象
                var newPermission = new Permissions
                {
                    PermissionName = permissionName
                };
                
                Console.WriteLine($"准备创建权限: Name={permissionName}");

                var result = await _permissionsService.CreatePermission(newPermission);
                if (result > 0)
                {
                    Console.WriteLine("权限添加成功");
                    return Json(new { success = true, message = "添加成功" });
                }
                else
                {
                    Console.WriteLine("权限添加失败，返回值为0");
                    return Json(new { success = false, message = "添加失败" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加权限异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return Json(new { success = false, message = $"添加失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<JsonResult> UpdatePermission(int id, string permissionName)
        {
            try
            {
                Console.WriteLine($"更新权限方法被调用，ID={id}, 权限名称={permissionName}");
                
                // 参数验证
                if (id <= 0)
                {
                    Console.WriteLine("无效的权限ID");
                    return Json(new { success = false, message = "无效的权限ID" });
                }
                
                if (string.IsNullOrEmpty(permissionName))
                {
                    Console.WriteLine("权限名称为空");
                    return Json(new { success = false, message = "权限名称不能为空" });
                }

                // 获取已存在的权限对象
                var existingPermission = await _permissionsService.GetPermissionById(id);
                if (existingPermission == null)
                {
                    Console.WriteLine($"找不到ID为{id}的权限");
                    return Json(new { success = false, message = $"找不到ID为{id}的权限" });
                }

                // 更新权限名称
                existingPermission.PermissionName = permissionName;
                
                // 提交更新后的对象
                var result = await _permissionsService.UpdatePermission(existingPermission);
                
                if (result > 0)
                {
                    Console.WriteLine("权限更新成功");
                    return Json(new { success = true, message = "更新成功" });
                }
                else
                {
                    Console.WriteLine("权限更新失败，返回值为0");
                    return Json(new { success = false, message = "更新失败" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新权限异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return Json(new { success = false, message = $"更新失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<JsonResult> DelPermission(int id)
        {
            try 
            {
                await _permissionsService.DelPermission(id);
                return Json(new { success = true, message = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"删除失败: {ex.Message}" });
            }
        }
    }
}
